using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Musi;
using Musi.Core.CSV;

public class ChooseChartEvent : ButtonPanel
{
    public ButtonPanel startPanel;

    public List<ChartPreview> chartPreviews;
    public TextAsset[] textAssets;

    public GameObject InfoPanel;
    public Text chartNameText;
    public Text descriptionText;

    public int page;
    public const int PAGE_CONTENT_SIZE = 6;

    private List<Vector2Int> chartButtonPositions;
    private List<Vector2Int> operateButtonPositions;
    private int chooseChart = -1;

    protected override void InitializeEvent()
    {
        if (chartButtonPositions == null || chartButtonPositions.Count <= 0)
        {
            chartButtonPositions = new List<Vector2Int>
            {
                new Vector2Int(0,0),
                new Vector2Int(0,1),
                new Vector2Int(0,2),
                new Vector2Int(1,0),
                new Vector2Int(1,1),
                new Vector2Int(1,2),
            };

            operateButtonPositions = new List<Vector2Int>
            {
                new Vector2Int(2,0),
                new Vector2Int(2,1),
                new Vector2Int(2,2),
            };
        }

        buttonManager.HideButton(chartButtonPositions);
        buttonManager.HideButton(operateButtonPositions);

        buttonManager.ChangeText(operateButtonPositions[0], "<size=60><</size>");
        buttonManager.ChangeText(operateButtonPositions[1], "Back");
        buttonManager.ChangeText(operateButtonPositions[2], "<size=60>></size>");

        buttonManager.ChangeOnClickEvent(operateButtonPositions[0], TurnLeft);
        buttonManager.ChangeOnClickEvent(operateButtonPositions[1], Back);
        buttonManager.ChangeOnClickEvent(operateButtonPositions[2], TurnRight);

        buttonManager.ChangeOnClickEvent(chartButtonPositions[0], () => { ClickChart(0, 0); });
        buttonManager.ChangeOnClickEvent(chartButtonPositions[1], () => { ClickChart(0, 1); });
        buttonManager.ChangeOnClickEvent(chartButtonPositions[2], () => { ClickChart(0, 2); });
        buttonManager.ChangeOnClickEvent(chartButtonPositions[3], () => { ClickChart(1, 0); });
        buttonManager.ChangeOnClickEvent(chartButtonPositions[4], () => { ClickChart(1, 1); });
        buttonManager.ChangeOnClickEvent(chartButtonPositions[5], () => { ClickChart(1, 2); });

        InfoPanel.SetActive(true);

        InitializeCSVPreviews();

        page = 1;

        ChangePage(page);
    }

    public void TurnLeft()
    {
        page--;
        if(!ChangePage(page))
        {
            page++;
        }
    }

    public void TurnRight()
    {
        page++;
        if(!ChangePage(page))
        {
            page--;
        }
    }

    public void Back()
    {
        InfoPanel.SetActive(false);
        chartNameText.text = "NULL";
        descriptionText.text = "NULL";
        startPanel.InitializeButtonPanel();
    }

    public void ClickChart(int x, int y)
    {
        int index = (page - 1) * PAGE_CONTENT_SIZE + x * 3 + y;
        if (index != chooseChart)
        {
            chooseChart = index;
        } 
        else
        {
            Chart chart = new Chart(chartPreviews[index]);
            CSVParser parser = new CSVParser(textAssets[index].text);
            List<ChartNote> notes = ChartNote.NotesParse(parser);
            chart.AddChartNotes(notes.ToArray());

            GameChartTransition.Instance.ChartInfo = chart;
            GameChartTransition.Instance.backScene = 0;
            SceneManager.LoadScene("GamingScene");

        }
        if (index >= 0 && index < chartPreviews.Count)
        {
            chartNameText.text = $"{chartPreviews[index].Name} - Maker: {chartPreviews[index].Maker}";
            descriptionText.text =
                $"Song: {chartPreviews[index].Song.name}\n\nLevel: {chartPreviews[index].Level}\n\nLength: {chartPreviews[index].Length}";
        }
    }

    private bool ChangePage(int page)
    {
        if (IsPageInRange(page))
        {
            for (int i = 0;i < chartButtonPositions.Count; i++)
            {
                buttonManager.ChangeText(chartButtonPositions[i], "");
                if ((page - 1) * PAGE_CONTENT_SIZE + i < chartPreviews.Count)
                    buttonManager.ChangeText(chartButtonPositions[i], chartPreviews[(page - 1) * PAGE_CONTENT_SIZE + i].Name);
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    private bool IsPageInRange(int page)
    {
        return // Bigger than 1
               page >= 1 && 
               // Equal or less than preview count
               (page * PAGE_CONTENT_SIZE <= chartPreviews.Count || 
               // Still have preview to show but can't fill one page
               (((page - 1) * PAGE_CONTENT_SIZE) < chartPreviews.Count && (page * PAGE_CONTENT_SIZE) > chartPreviews.Count));
    }

    private void InitializeCSVPreviews()
    {
        if (chartPreviews == null)
        {
            chartPreviews = new List<ChartPreview>();
        }

        if (chartPreviews.Count == 0)
        {
            textAssets = Resources.LoadAll<TextAsset>("Charts");
            for(int i = 0; i < textAssets.Length;i ++)
            {
                chartPreviews.Add(ChartPreview.GetFromCSV(new CSVParser(textAssets[i].text)));
            }
        }

        if (chartNameText == null || descriptionText == null)
        {
            Text[] texts = InfoPanel.GetComponentsInChildren<Text>();
            foreach (Text text in texts)
            {
                if (text.gameObject.name.ToLower() == "chartname")
                {
                    chartNameText = text;
                }
                else if (text.gameObject.name.ToLower() == "description")
                {
                    descriptionText = text;
                }
            }
        }
    }
}
